package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单功能
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,
                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String beginTime,
                        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器，并相关设置条件（单号，时间）
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(number != null, Orders::getNumber, number)
                .gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime)
                .lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);
        lqw.orderByDesc(Orders::getOrderTime);

        //进行分页查询
        orderService.page(pageInfo, lqw);

        return R.success(pageInfo);

    }

    /**
     * 用户端查看订单详情
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        log.info("查看订单详情...");
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);

        Long userId = BaseContext.getCurrentId();
        //构造条件构造器，并相关设置条件（订单更新时间）
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //只能查看自己的历史订单
        lqw.eq(userId!=null,Orders::getUserId,userId);
        lqw.orderByDesc(Orders::getOrderTime);
        //进行分页查询
        orderService.page(pageInfo, lqw);

        //基本数据进行拷贝
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        //获取records数据
        List<Orders> records = pageInfo.getRecords();
        //拷贝records数据
        LambdaQueryWrapper<OrderDetail> lqw1 = new LambdaQueryWrapper<>();
        List<OrdersDto> dtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            //获取订单id
            Long id = item.getId();
            //根据订单id查询对应的订单明细
            lqw1.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> list = orderDetailService.list(lqw1);
            //设置orderDto的订单明细属性
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(dtoList);

        return R.success(ordersDtoPage);
    }

    /**
     * 派送（更改订单状态）
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders) {
        //获取订单状态
        Integer status = orders.getStatus();
        //假如不为空，则修改订单状态
        if (status != null && status == 3) {
            orders.setStatus(3);
        }
        if (status != null && status == 4) {
            orders.setStatus(4);
        }

        orderService.updateById(orders);

        return R.success("订单状态修改成功");
    }

    /**
     * 再来一单
    * */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        //获得原来的订单和订单明细书局
        Long id = orders.getId();
        //订单数据
        Orders order = orderService.getById(id);
        //订单明细数据
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id!=null,OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(lqw);

        //复制原来订单表，并重新生成一个id
        Orders orders1 = new Orders();
        BeanUtils.copyProperties(order,orders1,"id");
        orders1.setStatus(2);
        orderService.save(orders1);

        //复制订单明细表，并重新生成id
        for (OrderDetail orderDetail : list) {
            OrderDetail orderDetail1 = new OrderDetail();
            BeanUtils.copyProperties(orderDetail,orderDetail1,"id");
            orderDetail.setOrderId(orders1.getId());
            orderDetailService.save(orderDetail1);
        }

        return R.success("下单成功");
    }

}
